package org.syyo.admin.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.syyo.admin.common.constant.FileConstant;
import org.syyo.admin.domain.FileUpload;
import org.syyo.admin.domain.ResultVo;
import org.syyo.admin.service.FileService;
import org.syyo.admin.utils.MyFileUtils;
import org.syyo.admin.utils.ResultUtils;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Auther: wangzhong
 * @Date: 2019/10/21 16:16
 * @Description:
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileConstant fileConstant;

    /**
     * 单个上传
     * @param file
     * @return
     */
    @Override
    public ResultVo uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        FileUpload fileUpdate = new FileUpload();
        // 获取文件名称
        String filename = file.getOriginalFilename();
        //判断文件类型，获取不同的文件存储路径
        String filePath = isFileType(filename);
        String sufname = filename.substring(filename.lastIndexOf("."));
        //uuid去除中间的 '-'
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileFullName = filePath + uuid + sufname;
        File dest = new File(fileFullName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try{
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        fileUpdate.setFileName(filename);
        fileUpdate.setUrl(fileFullName);



        return ResultUtils.response(fileUpdate);
    }

    /**
     * 判断文件类型
     * @param fileName
     * @return
     */
    private String isFileType(String fileName) {
        String filePath = null;
        if (MyFileUtils.isExcel(fileName)) {
            filePath = fileConstant.getExcelPath();
        } else {
            filePath = fileConstant.getImagePath();
        }
        return filePath;
    }

    /**
     * 删除文件
     * @param fileName
     * @return
     */
    @Override
    public boolean delFile(String fileName) {
        File file = new File(fileName);
        boolean flag = false;
        if (file.exists()&&file.isFile()){
            flag = file.delete();
            return flag;
        }
        return flag;
    }
}
